// pages/blog-academic/blog-academic.js
//违法违规内容
//特3456书yuuo莞6543李zxcz蒜7782法fgnv级
import formatTime from '../../utils/formatTime.js'
const db = wx.cloud.database()
let openid = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    blog: {},
    commentList: [],
    blogid: '',
    userInfo: {},
    isShow: true,
    collection: {
      status: false,
      text: "收藏",
      icon: "icon-shoucang"
    },
    zan: {
      status: false,
      text: "点赞",
      icon: "icon-dianzan"
    },
    postShang: {
      status: false,
      text: "打赏",
      icon: "icon-jifenxinxi"
    },
    commentContent: "", // 评论内容
    commentId: "",
    nomore: false,
    nodata: false,
    placeholder: "评论...",
    focus: false,
    toName: "",
    toOpenId: "",
    nodata_str: "暂无评论，赶紧抢沙发吧",
    bannerimg: [],
    num: {
      target: {
        dataset: {
          int: ''
        }
      }
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // console.log(options)
    this.setData({
      blogid: options.blogid
    })
    this._getBlogDetail()
    this._getPostRelated()

    this._getlogin()
    this._getbanner()
    // 打赏前工作，先查询个人乐豆
    this._getIntegral()

  },
  _getlogin: function() {
    wx.cloud.callFunction({
      name: "login"
    }).then(res => {
      openid = res.result.userInfo.openId
      db.collection('user').where({
        _id: openid
      }).limit(1).get().then(res =>{
        this.setData({
          userInfo : res.data[0]
        })
      })
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 获取blog信息
   * **/
  _getBlogDetail: async function() {
    wx.cloud.callFunction({
      name: 'seek',
      data: {
        blogId: this.data.blogid,
        $url: 'detail',
      }
    }).then((res) => {
      // console.log(res.result)
      res.result.detail[0].createTime = formatTime(new Date(res.result.detail[0].createTime))

      let commentList = res.result.commentList.data
      if (commentList.length === 0) {
        this.setData({
          nodata: true,
          blog: res.result.detail[0],
        })
      } else {
        this.setData({
          commentList,
          blog: res.result.detail[0],
        })
      }

    })
  },

  onPreviewImage(event) {
    // 图片预览
    const ds = event.target.dataset
    wx.previewImage({
      urls: ds.imgs,
      current: ds.imgsrc,
    })
  },

  /**
   * 收藏功能
   */
  postCollection: async function() {
    if (this.data.collection.status) {
      wx.cloud.callFunction({
        name: 'seek',
        data: {
          blogid: this.data.blogid,
          $url: 'delcollect'
        }
      }).then((res) => {
        // console.log(res.result)
        wx.showToast({
          title: '已取消收藏',
          icon: 'success',
          duration: 1500
        })
        this._getPostRelated()
        this._getBlogDetail()
      })
    } else {
      wx.cloud.callFunction({
        name: 'seek',
        data: {
          blogid: this.data.blogid,
          $url: 'addcollect'
        }
      }).then((res) => {
        // console.log(res.result)
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 1500
        })
        this._getPostRelated()
        this._getBlogDetail()
      })
    }
  },

  /**
   * 点赞功能
   */
  postZan: async function() {
    if (this.data.zan.status) {
      wx.cloud.callFunction({
        name: 'seek',
        data: {
          blogid: this.data.blogid,
          $url: 'delzan'
        }
      }).then((res) => {
        wx.showToast({
          title: '已取消点赞',
          icon: 'success',
          duration: 1500
        })
        this._getPostRelated()
        this._getBlogDetail()
      })
    } else {
      wx.cloud.callFunction({
        name: 'seek',
        data: {
          blogid: this.data.blogid,
          $url: 'addzan'
        }
      }).then((res) => {
        wx.showToast({
          title: '点赞成功',
          icon: 'success',
          duration: 1500
        })
        this._getPostRelated()
        this._getBlogDetail()
      })
    }
  },
  /**
   * 获取收藏和喜欢的状态
   */
  _getPostRelated: function() {
    wx.cloud.callFunction({
      name: 'seek',
      data: {
        blogid: this.data.blogid,
        $url: 'collect'
      }
    }).then(res => {
      // console.log(res.result)
      if (res.result.collect.length == 1) {
        this.setData({
          collection: {
            status: true,
            text: "收藏",
            icon: "icon-shoucang1"
          },
        })
      } else {
        this.setData({
          collection: {
            status: false,
            text: "收藏",
            icon: "icon-shoucang"
          },
        })
      }

      if (res.result.zan.length == 1) {
        this.setData({
          zan: {
            status: true,
            text: "点赞",
            icon: "icon-dianzan1"
          },
        })
      } else {
        this.setData({
          zan: {
            status: false,
            text: "点赞",
            icon: "icon-dianzan"
          },
        })
      }
    })
  },


  /**
   * 获取输入内容
   **/
  commentInput: function(e) {
    this.setData({
      commentContent: e.detail.value
    })
  },
  /**
   * 点击评论内容回复
   */
  focusComment: function(e) {
    // console.log(e)
    let that = this;
    let name = e.currentTarget.dataset.name;
    let commentId = e.currentTarget.dataset.id;
    let openId = e.currentTarget.dataset.openid;

    that.setData({
      commentId: commentId,
      placeholder: "回复" + name + ":",
      focus: true,
      toName: name,
      toOpenId: openId
    });
  },
  /**
   * 失去焦点时
   * @param {*} e 
   */
  onReplyBlur: function(e) {
    let that = this;
    const text = e.detail.value.trim();
    if (text === '') {
      that.setData({
        commentId: "",
        placeholder: "评论...",
        toName: ""
      });
    }
  },
  /**
   * 内容验证后上传
   */
  submitContent: async function(content, commentPage) {
    let that = this
    let checkResult = await wx.cloud.callFunction({
      name: 'postsService',
      data: {
        action: "checkPostComment",
        content: content,
      }
    })
    // wx.hideLoading()
    // console.log(checkResult)
    if (!checkResult.result) {
      wx.showToast({
        title: '评论内容存在敏感信息',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (that.data.commentId === "") {
      var data = {
        postId: that.data.blogid,
        cNickName: that.data.userInfo.nickName,
        cAvatarUrl: that.data.userInfo.avatarUrl,
        createDate: formatTime(new Date()),
        comment: content,
        childComment: [],
        flag: 1,
      }
      // 新增评论
      wx.cloud.callFunction({
        name: 'postsService',
        data: {
          action: "addPostComment",
          commentContent: data,
        }
      })

    } else {
      var childData = [{
        cNickName: that.data.userInfo.nickName,
        cAvatarUrl: that.data.userInfo.avatarUrl,
        createDate: formatTime(new Date()),
        comment: content,
        tNickName: that.data.toName,
        tOpenId: that.data.toOpenId,
        flag: 1,
        _id: Number(Math.random().toString().substr(3, 10) + Date.now()).toString(36),
      }]

      // 新增子评论
      wx.cloud.callFunction({
        name: 'postsService',
        data: {
          action: "addPostChildComment",
          id: that.data.commentId,
          comments: childData,
          postId: that.data.blogid,
        }
      })

    }

    await wx.cloud.callFunction({
      name: 'seek',
      data: {
        blogId: this.data.blogid,
        $url: 'detail',
      }
    }).then((res) => {
      // console.log(res.result)
      res.result.detail[0].createTime = formatTime(new Date(res.result.detail[0].createTime))

      let commentList = res.result.commentList.data
      if (commentList.length === 0) {
        this.setData({
          nodata: true,
          blog: res.result.detail[0],
        })
      } else {
        this.setData({
          commentList,
          blog: res.result.detail[0],
          commentContent: "",
          nomore: false,
          nodata: false,
          commentId: "",
          placeholder: "评论...",
          focus: false,
          toName: "",
          toOpenId: ""
        })
      }

      // console.log(res)
    })

    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 1500
    })
  },
  /**
   * 提交评论
   * @param {} e 
   */
  formSubmit: function(e) {
    try {
      let that = this;
      let commentPage = 1
      let content = that.data.commentContent;
      // console.info(content)
      if (content == undefined || content.length == 0) {
        wx.showToast({
          title: '请输入内容',
          icon: 'none',
          duration: 1500
        })
        return
      }
      that.submitContent(content, commentPage).then((res) => {
        this._getBlogDetail()
      })

    } catch (err) {
      wx.showToast({
        title: '程序有一点点小异常，操作失败啦',
        icon: 'none',
        duration: 1500
      })
      console.info(err)
      wx.hideLoading()
    }
  },
  // 获取广告
  _getbanner() {
    db.collection('banner').get().then((res) => {
      // console.log(res.data)
      var len = res.data.length
      var ran = Math.floor(Math.random() * len)
      this.setData({
        bannerimg: res.data[ran]
      })
    })
  },
  // 打赏弹出框
  postShang: function() {
    if (openid != this.data.blog._openid) {
      this.setData({
        showShangModal: true
      })
    } else {
      wx.showToast({
        title: '不能打赏自己的博客!',
        icon: 'none',
      })
    }
  },
  hideModal: function() {
    this.setData({
      showShangModal: false,
      num: {
        target: {
          dataset: {
            int: ''
          }
        }
      }
    })
  },
  // 打赏前工作，先查询个人乐豆
  _getIntegral: function() {
    wx.cloud.callFunction({
      name: 'seek',
      data: {
        $url: 'integral',
      }
    }).then((res) => {
      // console.log(res.result)
      this.setData({
        totalPoints: res.result[0].totalPoints
      })
    })
  },
  // 打赏操作
  addShang: function(e) {
    // 扣自己的乐豆
    if (e.target.dataset.int < this.data.totalPoints) {
      wx.showLoading({
        title: '打赏中',
      })
      wx.cloud.callFunction({
        name: 'integral',
        data: {
          openid,
          sense: 4, //0：看积分博客减积分，1:签到加积分，2需要积分的被查看，加给对方 3打赏加乐豆， 4打赏减乐豆
          continueDays: -e.target.dataset.int
        }
      }).then(() => {
        // 给对方加乐豆
        wx.cloud.callFunction({
          name: 'integral',
          data: {
            openid: this.data.blog._openid,
            sense: 3, //0：看积分博客减积分，1:签到加积分，2需要积分的被查看，加给对方 3打赏加乐豆， 4打赏减乐豆
            continueDays: Math.floor(e.target.dataset.int * 0.8)
          }
        }).then(() => {
          wx.hideLoading()
          wx.showToast({
            title: '打赏成功',
            icon: 'success'
          })
          this.hideModal()
          this._getIntegral()
        })
      })
    } else {
      wx.showToast({
        title: '您的乐豆不足',
        icon: 'none'
      })
    }
  },

  // 去个人主页
  gotoperhome(value) {
    let openid = value.currentTarget.dataset.openid
    wx.navigateTo({
      url: `../perhome/perhome?openid=${openid}`,
    })
  },

  // 自定义打赏
  shangInput: function(e) {
    // console.log(e.detail.value)
    this.setData({
      num: {
        target: {
          dataset: {
            int: e.detail.value
          }
        }
      }
    })

  },
  // 确定自定义打赏
  shangsend: function() {
    // console.log(this.data.num)
    if (this.data.num.target.dataset.int) {
      // console.log('aaaaa')
      this.addShang(this.data.num)
    } else {
      wx.showToast({
        title: '请输入数量!',
        icon: 'error',
      })
    }
  }
})